<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="98px">
      <el-form-item label="关联订单编号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入关联订单编号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="快递单号" prop="expressNo">
        <el-input v-model="queryParams.expressNo" placeholder="请输入快递单号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="物流单类型" prop="expressType">
        <el-select v-model="queryParams.expressType" placeholder="请选择物流单类型" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.EXPRESS_TYPE)"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.EXPRESS_STATUS)"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
                        type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                        :default-time="['00:00:00', '23:59:59']"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                   v-hasPermi="['system:order-express-info:create']">新增
        </el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading"
                   v-hasPermi="['system:order-express-info:export']">导出
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-edit" size="mini" @click="handleBatchConfirmTake"
                   v-hasPermi="['system:order-express-info:batchConfirmTake']">批量确认入库
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="id" align="center" prop="id"/>
      <el-table-column label="关联订单编号" align="center" prop="orderNo"/>
      <el-table-column label="快递单号" align="center" prop="expressNo"/>
      <el-table-column label="快递地址" align="center" prop="expressAddress"/>
      <el-table-column label="寄件人姓名" align="center" prop="name"/>
      <el-table-column label="手机号" align="center" prop="phone"/>
      <el-table-column label="取件日期" align="center" prop="preDate"/>
      <el-table-column label="取件时间" align="center" prop="preTime"/>
      <el-table-column label="物流单类型" align="center" prop="expressType">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.EXPRESS_TYPE" :value="scope.row.expressType"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.EXPRESS_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="用户快递费" align="center" prop="expressFee"/>
      <el-table-column label="描述" align="center" prop="remark"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button v-if="scope.row.status == 0" size="mini" type="text" icon="el-icon-edit" @click="handleConfirmTake(scope.row)"
                     v-hasPermi="['system:order-express-info:confirmTake']">确认入库
          </el-button>
          <el-button v-if="scope.row.status == 1" size="mini" type="text" icon="el-icon-edit" @click="handleRefundTake(scope.row)"
                     v-hasPermi="['system:order-express-info:refundTake']">退回物流
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="openLogisticsInfo(scope.row)"
                     v-hasPermi="['system:order-express-info:logisticsInfo']">物流信息
          </el-button>
<!--          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
                     v-hasPermi="['system:order-express-info:update']">修改
          </el-button>-->
<!--          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:order-express-info:delete']">删除
          </el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <OrderExpressInfoForm ref="formRef" @success="getList"/>


    <!-- 物流信息 -->
    <el-dialog title="物流信息" :visible.sync="openLogisticsInfoVisible" width="45%" v-dialogDrag append-to-body>
      <div style="height: 500px;  margin-top:20px; overflow-y: auto;" v-if="openLogisticsInfoData.routes">
        <el-steps direction="vertical" :active="1">
          <el-step v-for="item in openLogisticsInfoData.routes" :title="item.remark"
                   icon="el-icon-location" :description="item.acceptTime"></el-step>
        </el-steps>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openLogisticsInfoVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量确认入库 -->
    <el-dialog title="批量确认入库 (快递单号一行一个，最多支持50个)" :visible.sync="batchVisible" width="45%"
               :close-on-click-modal="false" :close-on-press-escape="false"
               v-dialogDrag append-to-body>
      <div style="margin-bottom: 20px; font-size: 16px; font-weight: bold;">快递数量：{{batchExpressNoNum}}</div>
      <el-input type="textarea" @input="countExpressNoNum"
                :autosize="{minRows: 20, maxRows: 20}"
                ref="batchExpressInput"
                v-model="batchExpressNos" placeholder="请输入快递单号(一行一个，最多支持50个)">
      </el-input>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchConfirmTake" :disabled="formLoading">确 定</el-button>
        <el-button @click="batchVisible = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import * as OrderExpressInfoApi from '@/api/system/orderexpressinfo';
import OrderExpressInfoForm from './OrderExpressInfoForm.vue';

export default {
  name: "OrderExpressInfo",
  components: {
    OrderExpressInfoForm,
  },
  data() {
    return {
      formLoading: false,
      openLogisticsInfoVisible: false,
      openLogisticsInfoData: {
        routes: []
      },
      batchVisible: false,
      batchExpressNos: '',
      batchExpressNoNum: 0,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单快递信息列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        orderNo: null,
        expressNo: null,
        expressType: null,
        status: null,
        createTime: [],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await OrderExpressInfoApi.getOrderExpressInfoPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除订单快递信息编号为"' + id + '"的数据项?')
      try {
        await OrderExpressInfoApi.deleteOrderExpressInfo(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有订单快递信息数据项?');
      try {
        this.exportLoading = true;
        const data = await OrderExpressInfoApi.exportOrderExpressInfoExcel(this.queryParams);
        this.$modal.msgSuccess("提交下载申请成功，稍后在下载记录中查看");
        // this.$download.excel(data, '订单快递信息.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
    /** 确认入库 */
    async handleConfirmTake(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认入库: 订单快递信息编号为"' + id + '"的数据项?')
      try {
        await OrderExpressInfoApi.confirmTake(id);
        await this.getList();
        this.$modal.msgSuccess("确认入库成功");
      } catch {
      }
    },

    /** 退回物流 */
    async handleRefundTake(row) {
      try {
        const { value  } = await this.$prompt('请输入备注', '退回物流', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^(?!\s*$).{1,100}$/,
          inputErrorMessage: '备注不能为空且长度不能超过100个字符'
        });
        console.log("remarks: ", value )
        await this.$modal.confirm('是否退回物流: 订单快递信息编号为"' + row.id + '"的数据项?');
        await OrderExpressInfoApi.refundTake({"id": row.id, "remark": value});
        await this.getList();
        this.$modal.msgSuccess("退回物流成功");
      } catch (error) {
      }
    },
    /** 物流信息 */
    async openLogisticsInfo(row) {
      this.openLogisticsInfoVisible = true
      const id = row.id;
      this.openLogisticsInfoData.routes = []
      const res = await OrderExpressInfoApi.logisticsInfo(id);
      if(res.data.apiResultData) {
        let apiResultData = JSON.parse(res.data.apiResultData)
        if(apiResultData && apiResultData.msgData && apiResultData.msgData.routeResps[0]) {
          this.openLogisticsInfoData.routes = apiResultData.msgData.routeResps[0].routes.slice().reverse()
        }
      }
    },
    async submitBatchConfirmTake() {
      if(!this.batchExpressNos) {
        this.$modal.msgError("请输入快递单号");
        return
      }
      const expressList = this.batchExpressNos.split("\n").map(item => item.trim()).filter(item => item)
      if(expressList.length > 50) {
        this.$modal.msgError("一次最多支持50个快递单号");
        return
      }
      await this.$modal.confirm('是否确认批量入库？');
      this.formLoading = true
      const res = await OrderExpressInfoApi.batchConfirmTake(expressList);
      await this.getList();
      this.$modal.msgSuccess("批量入库成功: " + res.data + "条, 失败: " + (this.batchExpressNoNum - res.data) + "条");
      this.formLoading = false
      this.batchExpressNos = ''
      this.batchExpressNoNum = 0
      // this.batchVisible = false
    },
    //批量确认入库
    async handleBatchConfirmTake() {
      this.batchVisible = false
      this.batchExpressNoNum = 0
      this.batchExpressNos = ''
      this.batchVisible = true
      this.$nextTick(() => {
        this.$refs.batchExpressInput.focus();
      });
    },
    async countExpressNoNum(val) {
      const expressList = this.batchExpressNos.split("\n").map(item => item.trim()).filter(item => item)
      this.batchExpressNoNum = expressList.length
    }

  }
};
</script>
